package com.liangtian.mdm.system.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.liangtian.mdm.base.controller.BaseController;
import com.liangtian.mdm.base.dao.JdbcDao;
import com.liangtian.mdm.base.exception.TransactionalException;
import com.liangtian.mdm.base.utils.CipherUtil;
import com.liangtian.mdm.base.utils.ResultObject;
import com.liangtian.mdm.base.utils.ShiroSessionUtils;
import com.liangtian.mdm.dm.common.page.JsonWrap;
import com.liangtian.mdm.system.log.SysLogUtil;
import com.liangtian.mdm.system.log.model.SysLogEnum;
import com.liangtian.mdm.system.log.service.SysLogService;
import com.liangtian.mdm.system.menu.model.Menu;
import com.liangtian.mdm.system.organization.model.SysOrganization;
import com.liangtian.mdm.system.organization.service.SysOrganizationService;
import com.liangtian.mdm.system.permission.model.SysRole;
import com.liangtian.mdm.system.permission.service.SysRoleService;
import com.liangtian.mdm.system.ugroup.model.SysUgroup;
import com.liangtian.mdm.system.user.model.SysUser;
import com.liangtian.mdm.system.user.service.SysUserService;
import com.liangtian.mdm.system.user.util.ExcelImport;
import com.liangtian.mdm.system.user.util.UserPassMd5;
import com.liangtian.mdm.util.ConstantBean;
import com.liangtian.mdm.util.ExportUtil;
import com.liangtian.mdm.util.RequestUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>Encoding    :  UTF-8</p>
 * <p>Package Name: com.liangtian.mdm.system.user.controller </p>
 * <p>Project Name: dm </p>
 * <p>Copyright   :  Copyright(c) 2016 石化盈科信息技术有限责任公司 </p>
 * <p>Created Time: 2016-06-15 11:41</p>
 * <p>Description : 用户实体</p>
 *
 * @author : beamzhang
 * @version :  1.0
 */
@Controller
@RequestMapping("/sysUser")
public class SysUserController extends BaseController {

    //注入用户服务接口
    @Autowired
    SysUserService sysUserService;

    //注入组织机构服务接口
    @Autowired
    SysOrganizationService sysOrganizationService;

    //注入角色接口对象
    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    JdbcDao jdbcDao;


    //日志服务接口对象
    @Autowired
    SysLogService sysLogService;

    private ExcelImport excelImport = new ExcelImport();

    //当前用户
    //@Value("${ConstantBean.CURRENT_SESSION_USER}")
    //private String ConstantBean.CURRENT_SESSION_USER;

    /**
     * @return 用户列表页面
     * @desc 用户页面的跳转
     */
    @RequestMapping(value = "/showSysUserList", method = RequestMethod.GET)
    public ModelAndView showUserList() {
        Map<String, Object> params = new HashMap<>();
        //获取组织机构数据
        List<Map<String, Object>> organizationList = sysOrganizationService.queryOrganizationList(params);
        view.addObject("organizationList", organizationList);
        view.setViewName("system/sysUser/page/sysUser_list");
        return view;
    }

    @RequestMapping(value = "/queryAllList", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject queryAllList(HttpServletRequest request, SysUser sysUser) {
        Map paramMap = RequestUtils.paramToMap(request, SysUser.class, false);

        PageInfo pageInfo = sysUserService.selectUserPageByCondition(paramMap);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);// JSONArray
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    /**
     * @return
     * @desc用户新增跳转
     */
    @RequestMapping(value = "showSysUserAdd", method = RequestMethod.GET)
    public ModelAndView showUserAdd() {
        view.setViewName("system/sysUser/page/sysUser_add");
        return view;
    }

    /**
     * @return
     * @desc用户修改页面跳转
     */
    @RequestMapping(value = "showSysUserUpdate", method = RequestMethod.GET)
    public ModelAndView showSysUserUpdate(Long[] ids) {
        SysUser user = new SysUser();
        if (ids.length > 0) {
            user.setUserId(ids[0]);
            user = sysUserService.selectUserById(user);
            Map<String, Object> params = new HashMap<>();
            SysRole role = new SysRole();
            role.setRoleStatus(1);
            params.put("organizationStatus", 1);
            //获取组织机构数据
            List<Map<String, Object>> organizationList = sysOrganizationService.queryOrganizationList(params);
            view.addObject("organizationList", organizationList);
            //获取当前用户的角色信息
            List<Map<String, Object>> roleList = sysRoleService.queryAllRoleList(role);
            List<SysRole> roles = sysUserService.selectRole(user);
            if (roles.size() > 0) {
                for (Map all : roleList) {
                    look:
                    for (SysRole own : roles) {
                        if (all.get("roleId").toString().equals(own.getRoleId() + "")) {
                            all.remove("roleFlag");
                            all.put("roleFlag", "2");
                            break look;
                        }
                    }
                }
            }
            view.addObject("roleList", roleList);
        }
        view.addObject("user", user);
        view.setViewName("system/sysUser/page/sysUser_edit");
        return view;
    }

    /**
     * @param user 对象
     * @return
     * @desc 获取用户的全部数据
     */
    @RequestMapping(value = "/queryAllUserList", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject queryAllUserList(HttpServletRequest request, SysUser user) {
        Map paramMap = RequestUtils.paramToMap(request, SysUser.class, false);
        PageInfo pageInfo = sysUserService.selectUserPageByCondition(paramMap);
        ResultObject result = new ResultObject(pageInfo, user.getDraw());
        return result;
    }

    /**
     * 修改用户状态（启用， 禁用）
     *
     * @param ids
     * @param status
     * @return
     */
    @RequestMapping(value = "/editUserStatus", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject editUserStatus(Long[] ids, Long status, HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        List<Long> idsList = Arrays.asList(ids);
        params.put("idsList", idsList);
        params.put("userStatus", status);
        int count = 0;
        /*//获取session中用户
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        SysLog sysLog = new SysLog();
        Date date = new Date();
        sysLog.setUserName(user.getUserName());
        sysLog.setOperationType("4");
        sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
        sysLog.setOperationDate(date);*/
        try {
            //启用，禁用操作
            count = sysUserService.editUserStatus(params);
            if (count > 0) {
                if (status == 1) {
                    SysLogUtil.insertLog("用户启用",
                            SysLogEnum.SYS_USER.getCode(), SysLogEnum.QY.getCode(), request);
                } else {
                    SysLogUtil.insertLog("用户停用",
                            SysLogEnum.SYS_USER.getCode(), SysLogEnum.TY.getCode(), request);
                }
            }
           /* //成功记录操作日志
            sysLogServiceImpl.insertLog(sysLog);*/
        } catch (Exception e) {
           /* if(status == 1) {
                sysLog.setOperationContent("用户【"+user.getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",启用用户失败");
            }else{
                sysLog.setOperationContent("用户【"+user.getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",禁用用户失败");
            }
            //失败记录操作日志
            sysLogServiceImpl.insertLog(sysLog);*/
            e.printStackTrace();
        }
        ResultObject result = new ResultObject(count, "编辑用户状态成功", "编辑用户状态失败");
        return result;
    }

    /**
     * 批量删除用户
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/batchDeleteUser", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject batchDeleteUser(Long[] ids, HttpServletRequest request) throws TransactionalException {
        Map<String, Object> params = new HashMap<>();
        List<Long> idsList = Arrays.asList(ids);
        params.put("idsList", idsList);
        int count = 0;
        /*//获取session中用户
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        SysLog sysLog = new SysLog();
        Date date = new Date();
        sysLog.setUserName(user.getUserName());
        sysLog.setOperationType("5");
        sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
        sysLog.setOperationDate(date);*/
        try {
            //删除用户
            count = sysUserService.batchDeleteUser(params);
            SysLogUtil.insertLog("删除用户",
                    SysLogEnum.SYS_USER.getCode(), SysLogEnum.SC.getCode(), request);
            /*if (count > 0) {
                sysLog.setOperationContent("用户【"+user.getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",删除用户成功");
            }
            //成功记录操作日志
            sysLogServiceImpl.insertLog(sysLog);*/
        } catch (Exception e) {
            /*sysLog.setOperationContent("用户【"+user.getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",删除用户失败");
            //失败记录操作日志
            sysLogServiceImpl.insertLog(sysLog);*/
            e.printStackTrace();
        }
        ResultObject result = new ResultObject(count, "删除用户成功", "删除用户失败");
        return result;
    }

    /**
     * 修改用户
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject updateUser(SysUser user, Long[] ids, HttpServletRequest request) throws TransactionalException {
        int count = 0;
        //获取session中用户
        SysUser sysUser = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        /*SysLog sysLog = new SysLog();
        Date date = new Date();
        sysLog.setUserName(sysUser.getUserName());
        sysLog.setOperationType("4");
        sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
        sysLog.setOperationDate(date);*/
        try {
            //删除用户操作
            count = sysUserService.updateUser(user, ids);
            SysLogUtil.insertLog("编辑用户",
                    SysLogEnum.SYS_USER.getCode(), SysLogEnum.BJ.getCode(), request);
            /*if (count > 0) {
                sysLog.setOperationContent("用户【"+sysUser.getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",修改用户成功");
            }
            //成功记录操作日志
            sysLogServiceImpl.insertLog(sysLog);*/
        } catch (TransactionalException e) {
            /*sysLog.setOperationContent("用户【"+sysUser.getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",修改用户失败");
            //失败记录操作日志
            sysLogServiceImpl.insertLog(sysLog);*/
            e.printStackTrace();
        }
        ResultObject result = new ResultObject(count, "修改用户成功", "修改用户失败");
        return result;
    }

    /**
     * 校验用户账号
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/sameUserAccountValidate", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject sameUserAccountValidate(SysUser user) {
        ResultObject result = new ResultObject();
        Map<String, Object> params = new HashMap<>();
        if (null != user) {
            if (null != user.getUserAccount() && !"".equals(user.getUserAccount())) {
                params.put("userAccount", user.getUserAccount());
            }
            if (null != user.getUserId() && !"".equals(user.getUserId())) {
                params.put("userId", user.getUserId());
            }
        }
        int count = sysUserService.selectUserAccount(params);
        if (count > 0) {
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 查询未提交的用户列表
     *
     * @param request
     * @param sysUser
     * @return
     */
    @RequestMapping(value = "/queryUserListWithNotSubmit", method = RequestMethod.POST)
    @ResponseBody
    @SuppressWarnings("rawtypes")
    public JSONObject queryUserListWithNotSubmit(HttpServletRequest request, SysUser sysUser) {
        Map<String, Object> paramMap = RequestUtils.paramToMap(request, SysUser.class, false);
        PageInfo pageInfo = sysUserService.selectUserListWithNotSubmit(paramMap);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);// JSONArray
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    //查询用户信息
    @RequestMapping(value = "/queryUserList", method = RequestMethod.POST)
    @ResponseBody
    @SuppressWarnings("rawtypes")
    public JSONObject queryUserList(HttpServletRequest request, SysUser sysUser) {
        Map<String, Object> paramMap = RequestUtils.paramToMap(request, SysUser.class, false);
        PageInfo pageInfo = sysUserService.selectUserListByCondition(paramMap);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);// JSONArray
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    //查询用户信息
    @RequestMapping(value = "/queryUsers", method = RequestMethod.POST)
    @ResponseBody
    @SuppressWarnings("rawtypes")
    public JSONObject queryUsers(HttpServletRequest request, SysUser sysUser) {
        Map<String, Object> paramMap = RequestUtils.paramToMap(request, SysUser.class, false);
//		String users= request.getParameter("userIds");
        PageInfo pageInfo = sysUserService.queryUsers(paramMap);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);// JSONArray
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    /**
     * * <p>Title: 查询不是本用户下，所有活动用户</p>
     * <p>Description: TODO </p>
     * <p>Company:@param request
     * <p>Company:@param sysUser
     * <p>Company:@return </p>
     *
     * @author : xiaoliu
     * @date :2016年11月3日下午4:05:13
     */
    @RequestMapping(value = "/queryUserListWithoutUserId", method = RequestMethod.POST)
    @ResponseBody
    @SuppressWarnings("rawtypes")
    public JSONObject queryUserListWithoutUserId(HttpServletRequest request, SysUser sysUser) {
        Map<String, Object> paramMap = RequestUtils.paramToMap(request, SysUser.class, false);
        PageInfo pageInfo = sysUserService.queryUserListWithoutUserId(paramMap);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);// JSONArray
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }


    /**
     * * <p>Title: 用户审核操作，查询出来的数据</p>
     * <p>Description: TODO </p>
     * <p>Company:@param request
     * <p>Company:@param sysUser
     * <p>Company:@return </p>
     *
     * @author : xiaoliu
     * @date :2016年11月2日下午1:21:20
     */

    @RequestMapping(value = "/queryShUserList", method = RequestMethod.POST)
    @ResponseBody
    @SuppressWarnings("rawtypes")
    public JSONObject queryShUserList(HttpServletRequest request, SysUser sysUser) {
        Map<String, Object> paramMap = RequestUtils.paramToMap(request, SysUser.class, false);
        PageInfo pageInfo = sysUserService.selectShUserListByCondition(paramMap);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);// JSONArray
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }


    @RequestMapping(value = "/selectUserByUserId", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject selectUserByUserId(HttpServletRequest request, SysUser sysUser) {
        SysUser user = sysUserService.selectUserById(sysUser);
        List<SysUser> userList = new ArrayList<SysUser>();
        userList.add(user);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", userList);
        jsonObject.put("total", 1);
        return jsonObject;
    }

    /**
     * 查询用户信息
     *
     * @param request
     * @param sysUser
     * @return
     */
    @RequestMapping(value = "/selectUserWithOrganizaNameById", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject selectUserById(HttpServletRequest request, SysUser sysUser) {
        Map<String, Object> sysUserResult = sysUserService.selectUserWithOrganizaNameById(sysUser);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user", sysUserResult);
        return jsonObject;
    }

    /**
     * 查询用户组
     *
     * @param request
     * @param sysUser
     * @return
     */
    @RequestMapping(value = "/selectUserGroup", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject selectUserGroup(HttpServletRequest request, SysUser sysUser) {

//    	List<Map<String, Object>> userGroup = sysUserServiceImpl.selectUserGroup(sysUser);
        List<Map<String, Object>> userGroup = sysUserService.selectUserGroup(sysUser.getUserId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userGroup", userGroup);
        return jsonObject;
    }

    /**
     * 查询用户角色
     *
     * @param request
     * @param sysUser
     * @return
     */
    @RequestMapping(value = "/selectRole", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject selectRole(HttpServletRequest request, SysUser sysUser) {
        List<SysRole> sysRole = sysUserService.selectRole(sysUser);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sysRole", sysRole);
        return jsonObject;
    }

    /**
     * 查询菜单树
     *
     * @param request
     * @param menu
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryMenuTree", method = RequestMethod.POST)
    public String queryMenuTree(HttpServletRequest request, Menu menu, SysUser user) {
        List<Menu> menuLst = new ArrayList<Menu>();
        ResultObject result = new ResultObject();
        Map<String, Object> paramMap = RequestUtils.paramToMap(request, Menu.class, false);
        if (null != user.getUserId() && !"".equals(user.getUserId())) {
            paramMap.put("userId", user.getUserId());
        }
        try {
            menuLst = sysUserService.menuTree(paramMap); //查询菜单树
            result.setData(menuLst);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(menuLst);
    }

    /**
     * 查询所有用户组
     *
     * @param request
     * @param menu
     * @return
     */
    @RequestMapping(value = "/queryUserGroupList", method = RequestMethod.POST)
    @ResponseBody
    public String queryUserGroupList(HttpServletRequest request) {
        Map<String, Object> paramMap = RequestUtils.paramToMap(request, SysUgroup.class, false);
        PageInfo pageInfo = sysUserService.queryUserGroupList(paramMap);

        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);
        jsonObject.put("total", pageInfo.getTotal());

        return JsonWrap.toJSONString(jsonObject);
    }

    /**
     * 查询用户所属的用户组
     *
     * @param request
     * @param menu
     * @return
     */
    @RequestMapping(value = "/queryTheUserGroup", method = RequestMethod.POST)
    @SuppressWarnings("rawtypes")
    @ResponseBody
    public String queryTheUserGroup(HttpServletRequest request) {
        Map<String, Object> paramMap = RequestUtils.paramToMap(request);
        PageInfo pageInfo = sysUserService.queryTheUserGroup(paramMap);
        System.out.print("userId:" + request.getParameter("userId"));
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);
        jsonObject.put("total", pageInfo.getTotal());

        return JsonWrap.toJSONString(jsonObject);
    }

    /**
     * 批量新增用户组用户
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/insertUserGroup", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject insertUserGroup(HttpServletRequest request) throws TransactionalException {
        Map<String, Object> param = RequestUtils.paramToMap(request);
        String id = request.getParameter("groupIds");
        String[] groupIds = id.split(",");
        param.put("groupIds", groupIds);
        String userId = request.getParameter("userId");
        param.put("userId", userId);
        boolean ret = false;

        ret = sysUserService.insertUserGroup(param);

        int f = ret == true ? 1 : 0;
        ResultObject result = new ResultObject(f, "新增用户组成功", "新增用户组失败");
        return result;
    }

    //新增用户
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject addUser(SysUser sysUser, HttpServletRequest request) {
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        sysUser.setUserCreateId(user.getUserId());//创建人
        sysUser.setUserStatus("0");//状态
        sysUser.setUserSalt("dm");
        //String pwd = CipherUtil.createPwdEncrypt(sysUser.getUserName(), sysUser.getUserPassword(), sysUser.getUserSalt());
        String pwd = CipherUtil.createPwdEncrypt(sysUser.getUserAccount().trim(), sysUser.getUserPassword().trim(), sysUser.getUserSalt().trim());
        sysUser.setUserPassword(pwd);
        int count = sysUserService.addUser(sysUser);
        ResultObject resultObject = new ResultObject(count, "新增成功", "新增失败");
        return resultObject;
    }

    /**
     * 批量删除用户组
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/deleteUserGroup", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject batchDeleteUgroup(String[] groupIds, HttpServletRequest request) throws TransactionalException {
        Map<String, Object> params = new HashMap<>();
        List<String> idsList = Arrays.asList(groupIds);
        params.put("idsList", idsList);
        String userId = request.getParameter("userId");
        params.put("userId", userId);
        boolean flag = false;

        flag = sysUserService.deleteUserGroup(params);

        int f = flag == true ? 1 : 0;
        ResultObject result = new ResultObject(f, "删除用户组成功", "删除用户组失败");
        return result;
    }

    /**
     * 审核
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/approve", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject approve(HttpServletRequest request) {

        List<SysUser> list = new ArrayList<SysUser>();

//			Map<String, Object> param = new HashMap<>(); 
//			//审核信息
//			param.put("infos", request.getParameter("infos"));
//			//表名
//			String tableName = request.getParameter("tableName");
//			param.put("tableName", tableName);

        //修改数据ID
        String infos = request.getParameter("infos");
        //组装信息 ID ♀ opinion ♀ Y/N ♀ operType
        String[] items = infos.split("♂");
        //前端拼接的字符，传递到后台，需要重新解析
        //infos.push(rows[i].userId+"♀"+opinion+"♀"+state+"♀"+rows[i].userStatus);
        for (String item : items) {
            SysUser user = new SysUser();
            String[] info = item.split("♀");
            String userId = info[0];//第一个保存的是用户的userId
//				String options = info[1];//同意----不同意的条件
            String isY = info[2];//T-审核通过，F-审核拒绝
            String userStatus = info[3];//前端传来用户操作状态 D-批量已提交   T-待冻结  w-待活动

            if (isY.equals("T")) {
                user.setUserId(Long.parseLong(userId));
                if (userStatus.equals("D") || userStatus.equals("W")) {
                    // 设置用户状态：活动用户
                    user.setUserStatus("A");
                } else if (userStatus.equals("T")) {
                    // 设置用户状态：冻结用户
                    user.setUserStatus("F");
                }

            } else {
                user.setUserId(Long.parseLong(userId));
                if (userStatus.equals("D")) {
                    // 设置用户状态：拒绝，R已驳回，审核没通过
                    user.setUserStatus("R");
                } else if (userStatus.equals("T")) {
                    // 设置用户状态：活动用户
                    user.setUserStatus("A");
                } else if (userStatus.equals("W")) {
                    // 设置用户状态：未激活
                    user.setUserStatus("F");
                }

            }

            list.add(user);
        }

        int ret = sysUserService.approve(list);
        int f = ret < 0 ? 1 : 0;
        ResultObject result = new ResultObject(f, "审核成功", "审核失败");
        return result;
    }

    /**
     * 用户批量创建_数据删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject delete(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        if (ids == null || "".equals(ids))
            return null;

        Map<String, Object> map = new HashMap<>();
        map.put("idsList", ids.split(","));
        map.put("tableName", request.getParameter("tableName"));

        int ret = sysUserService.delete(map);
        int f = ret > 0 ? 1 : 0;
        ResultObject result = new ResultObject(f, "删除成功", "删除失败");
        return result;
    }

    /**
     * 重置用户密码
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/resetPass", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject resetPass(HttpServletRequest request) {
        ResultObject result = null;
        try {
            String ids = request.getParameter("ids");
            List<SysUser> suLst = sysUserService.selectUserByIds(ids);
            suLst = UserPassMd5.userPassEncrypt(request, suLst, true);
            int ret = sysUserService.resetPass(suLst);
            int f = ret < 0 ? 1 : 0;
            result = new ResultObject(f, "重置成功", "重置失败");
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResultObject(0, "重置成功", "重置失败");
        }

        return result;
    }


    /**
     * 批量冻结 ，解冻数据
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/updateByIds", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject updateByIds(HttpServletRequest request) {
        System.out.println(request);
        String ids = request.getParameter("ids");//获取需要操作的用户id集合
        String str = request.getParameter("str");//根据这个字符值判断是冻结操作还是解冻操作
        if (ids == null || "".equals(ids))
            return null;

        Map<String, Object> map = new HashMap<>();
        map.put("idsList", ids.split(","));
        map.put("str", str);
        int ret = sysUserService.updateByIds(map);
        int f = ret > 0 ? 1 : 0;
        ResultObject result = new ResultObject(f, "操作成功", "操作失败");
        return result;
    }


    /**
     * 用户批量创建_提交
     * String tableName, @RequestParam("ids[]") List<String> ids
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject submit(HttpServletRequest request) {
        Map<String, Object> param = new HashMap<>();
        String ids = request.getParameter("ids");
        param.put("ids", ids);
        param.put("tableName", request.getParameter("tableName"));

        int ret = sysUserService.submit(param);
        int f = ret < 0 ? 1 : 0;
        ResultObject result = new ResultObject(f, "提交成功", "提交失败");
        return result;
    }

    /**
     * 修改用户
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject updateUser(SysUser user, HttpServletRequest request) {
        int count = 0;
        //修改用户
        String userStr = request.getParameter("user");
        SysUser sysUser = (SysUser) JSONObject.parseObject(userStr, SysUser.class);
        count = sysUserService.updateUser(sysUser);

        ResultObject result = new ResultObject(count, "修改用户成功", "修改用户失败");
        return result;
    }

    /**
     * 导出模板
     *
     * @param modelId
     * @param tableName
     */
    @RequestMapping(value = "tempExport", method = RequestMethod.GET)
    @ResponseBody
    public void templeExport(HttpServletResponse response, HttpServletRequest request) {
        sysUserService.templeExport(response);
    }

    /**
     * 导入用户
     *
     * @param modelId
     * @param tableName
     * @return
     */
    @RequestMapping(value = "excelImport", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject excelImport(HttpServletResponse response, HttpServletRequest request) {
        ResultObject result = null;
        try {
            String tableName = request.getParameter("tableName");
            MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = mulRequest.getFile("excel");

            // 获取路径
            String ctxPath = request.getSession().getServletContext().getRealPath("/") + "upload" + File.separator;
            // 创建文件
            File dirPath = new File(ctxPath);
            if (!dirPath.exists()) {
                dirPath.mkdir();
            }
            File uploadFile = new File(ctxPath + file.getOriginalFilename());

            // 保存上传的文件到服务器发布项目中的upload文件夹下
            FileCopyUtils.copy(file.getBytes(), uploadFile);

            Workbook book = ExcelImport.getWorkbook(uploadFile);
            Sheet sheet = book.getSheetAt(0);
            List<Object[]> valueList = ExcelImport.read(sheet);
            // 插入数据
            if (valueList != null && valueList.size() > 0) {
                result = checkImportList(valueList, tableName, request);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /*
     * @description:向数据库表中插入数据(1000行插入一次)
     * @param tableName,conn,sqlStr,subList,headArray
     * @return
     * @time:2016年9月07日
     */
    public List<String> genSql(String tableName, List<Object[]> subList, String[] headArray, HttpServletRequest request) {
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);

        List<String> sqls = new ArrayList<String>();
        String user_salt = "dm";
//		String user_pswd = "111111";
        // 获取值集合
        for (int j = 0; j < subList.size(); j++) {
            StringBuffer sb = new StringBuffer("");
            sb.append(" insert into " + tableName + " (USER_ID,")
                    .append("USER_ACCOUNT,USER_NAME, USER_EMAIL, USER_PHONE, USER_TELEPHONE, ORGANIZATION_ID,")
                    .append("USER_STATUS, USER_CREATE_DATE, USER_CREATE_ID, USER_PASSWORD, USER_SALT)")
                    .append(" VALUES( SYS_USER_SEQ.nextval,");

            String pwd = "";
            String[] row = (String[]) subList.get(j);
            for (int k = 0; k < row.length; k++) {
                if (k == 0) {//用户账号
                    sb.append("'").append(row[k].trim()).append("',");
                } else if (k == 1) {//用户名称
                    sb.append("'").append(row[k].trim()).append("',");
                } else if (k == 2) {//用户密码
                    //这块越哥要改生成密码这块逻辑
//					pwd = CipherUtil.createPwdEncrypt(row[k].trim(), user_pswd.trim(), user_salt.trim());
                    pwd = UserPassMd5.userPassEncryptToString(request, row[k - 2].trim(), row[k].trim(), user_salt);
                } else if (k == 3) {//用户邮箱
                    sb.append("'").append(row[k].trim()).append("',");
                } else if (k == 4) {//用户电话
                    if (row[k].trim().equals("")) {
                        sb.append("'").append("',");
                    } else {
                        sb.append("'").append(row[k].trim()).append("',");
                    }
                } else if (k == 5) {//用户手机
                    sb.append("'").append(row[k].trim()).append("',");
                } else if (k == 6) {//所属公司
                    String orgName = row[k].trim();
                    List<SysOrganization> orgLst = sysOrganizationService.queryOrgByName(orgName);
                    if (orgLst.size() > 0) {//如果组织机构大于0
                        for (SysOrganization sys : orgLst) {
                            sb.append("'").append(sys.getOrganizationId()).append("',");
                        }
                    }
                }

            }
            sb.append("'0', sysdate, ").append(user.getUserId()).append(", '")
                    .append(pwd).append("', '").append(user_salt).append("')");
            sqls.add(sb.toString());
        }
        return sqls;
    }

    /**
     * 用户权限复制
     *
     * @param oper操作类型（所有权限、视图权限、按钮权限、菜单权限）
     * @param userId                        谁的权限
     * @RequestParam("ids[]") List<String> ids 复制给哪些用户
     */
    @RequestMapping(value = "/copyUserAuthority", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject copyUserAuthority(HttpServletRequest request) {
        Map<String, Object> param = new HashMap<>();
        ResultObject result = null;
        //获取操作类型
        String oper = request.getParameter("oper");
        //获取权限用户的userid
        String userId = request.getParameter("userId");
        //获取需要赋值权限的用户id
        String ids = request.getParameter("ids");
        param.put("ids", ids);
        param.put("userId", userId);
        if (oper.equals("Btn")) {//如果是按钮权限
            int retBtn = sysUserService.updateUserButtonAuthority(param);//按钮权限
            int f = retBtn > -1 ? 1 : 0;
            result = new ResultObject(f, "按钮权限复制成功", "按钮权限复制失败");
        } else if (oper.equals("View")) {
            int retGoup = sysUserService.updateUserGroupAuthority(param);//视图权限
            int f = retGoup > -1 ? 1 : 0;
            result = new ResultObject(f, "视图权限复制成功", "视图权限复制失败");
        } else if (oper.equals("Menu")) {
            int retMenu = sysUserService.updateUserMenuAuthority(param);//菜单权限
            int f = retMenu > -1 ? 1 : 0;
            result = new ResultObject(f, "菜单权限复制成功", "菜单权限复制失败");
        } else if (oper.equals("All")) {
            int ret1 = sysUserService.updateUserButtonAuthority(param);//按钮权限
            int ret2 = sysUserService.updateUserGroupAuthority(param);//视图权限
            int ret3 = sysUserService.updateUserMenuAuthority(param);//菜单权限
            int f = ret1 + ret2 + ret3 > -1 ? 1 : 0;
            result = new ResultObject(f, "所有权限复制成功", "所有权限复制失败");
        }
        return result;
    }

    /**
     * * <p>Title: 校验用户输入的数据</p>
     * <p>Company:@param valueList
     * <p>Company:@param tableName
     * <p>Company:@param conn
     * <p>Company:@return </p>
     *
     * @author : xiaoliu
     * @date :2016年10月27日下午2:20:26
     */
    @RequestMapping(value = "/checkImportList", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject checkImportList(List<Object[]> valueList, String tableName, HttpServletRequest request) {
        //ExcelUtil eu=new ExcelUtil();
        String fileName = "";
        ResultObject resuObj = null;
        StringBuffer sb = new StringBuffer();//声明拼接符
        //去掉导入文件的表头==及从第二行开始算输入数据
        valueList.remove(0);//去掉第一行
        valueList.remove(0);//去掉第二行
        //这样的话，说明模板里面存在数据
        if (valueList.size() > 0) {
            //首先校验，当前导入数据这个批次里面，用户账号是否有重复
            Map<String, Object> checkAccMap = checkAccountImport(valueList, tableName);
            //同批导入数据之间的校验
            boolean flag = (boolean) checkAccMap.get("flag");
            if (!flag) {//如果flag是false,说明那个模板中，同批数据用户账号存在重复
                //报错，提示导入失败原因--因为是同批导入数据之间用户账号，存在重复
                String errorRec = (String) checkAccMap.get("checkResult");
                fileName = "userImportError" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
                try {
                    ExportUtil.errTxt(errorRec.toString(), fileName);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                resuObj = new ResultObject("false", fileName);
            } else {
                //如果同批次导入的没有问题，就需要查询数据库，跟sys_user表里面的数据进行数据校验
                Map<String, Object> checkTabMap = checkTabAcctImport(valueList, tableName);
                boolean tflag = (boolean) checkTabMap.get("tflag");
                if (!tflag) {//如果flag是false,说明那个模板中，同批数据用户账号存在重复
                    //报错，提示导入失败原因--因为是同批导入数据之间用户账号，存在重复
                    String errorTab = (String) checkTabMap.get("checkTabResult");
                    fileName = "userImportError" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
                    try {
                        ExportUtil.errTxt(errorTab.toString(), fileName);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    resuObj = new ResultObject("false", fileName);
                } else {
                    for (int j = 0; j < valueList.size(); j++) {//获取用户将导入的数据n条
                        String[] row = (String[]) valueList.get(j);//获取行
                        for (int k = 0; k < row.length; k++) {
                            String cell = row[k];//获取每固定行一列（0,0）
                            sb.append(check_column(j, k, cell));
                        }

                    }
                    if (sb.toString().equals("")) {
                        String[] headArray = {"USER_ACCOUNT", "USER_NAME", "USER_PASSWORD", "USER_EMAIL", "USER_PHONE", "USER_TELEPHONE", "ORGANIZATION_ID"};
                        List<String> sqls = genSql(tableName, valueList, headArray, request);
                        boolean sucess = jdbcDao.executeSqlList(sqls, true);
                        if (sucess) {
                            resuObj = new ResultObject("true", "导入成功!");
                        }
                    } else {
                        fileName = "userImportError" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
                        try {
                            ExportUtil.errTxt(sb.toString(), fileName);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        resuObj = new ResultObject("false", fileName);
                    }

                }

            }
        } else {
            resuObj = new ResultObject("true", "导入成功!");
        }
        return resuObj;
    }

    public String check_column(int row, int column, String cell) {
        StringBuffer sb = new StringBuffer();//声明拼接符
        //校验每行数据的每一列，错误的拼接成string，正确的不拼接
        if (column == 0) {//说明是第一列（校验用户账号）
            if (cell.trim().equals("") || cell.trim() == null) {//如果数据为空
                sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,用户账号为空为空！\r\n");
            } else if (cell.trim().length() > 30) {//长度大于30
                sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,用户账号输入长度应小于或等于30！\r\n");
            } else {
                //去数据库查询，用户账号是否已经使用啦
                int count = sysUserService.queryExistByAccount(cell.trim());
                if (count > 0) {
                    sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,用户账号重复!\r\n");
                }
            }
        } else if (column == 1) {//说明是第二列（校验用户名称）
            if (cell.trim().equals("") || cell.trim() == null) {
                sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,用户名称不可为空！\r\n");
            } else {
                if (cell.trim().length() > 30) {
                    sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,用户名称输入长度应小于或等于30！\r\n");
                }
            }
        } else if (column == 2) {//校验密码
            if (cell.trim().equals("") || cell.trim() == null) {
                sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,用户密码不可为空！\r\n");
            } else {
                if (cell.trim().length() > 30) {
                    sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,用户密码输入长度应小于或等于30！\r\n");
                } else {
//						  try{
//						    	//校验邮箱格式是否正确
//								 String check = "^\\w+$";//校验密码，只能输入由数字、26个英文字母或者下划线
//								 Pattern p = Pattern.compile(check);  
//								 Matcher m = p.matcher(cell.trim());
//								 System.out.println(m.matches());
//								 if(!m.matches()){
//									 sb.append("@@导入数据第"+(row+1)+"行,第"+(column+1)+"列,不符合密码的填写格式!\r\n");
//								 }
//				            }catch(Exception e){
                    //手动捕捉异常
//							    	  sb.append("@@导入数据第"+(row+1)+"行,第"+(column+1)+"列,不符合密码的填写格式!\r\n");
//				            }  
                }
            }
        } else if (column == 3) {//说明是第三列（校验用户邮箱）
            if (cell.trim().equals("") || cell.trim() == null) {
                sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,用户邮箱为空！\r\n");
            } else {

                if (cell.trim().length() > 50) {
                    sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,用户邮箱输入长度应小于或等于50！\r\n");
                } else {
                    try {
                        //校验邮箱格式是否正确
//					    	^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$
                        String check = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
                        Pattern p = Pattern.compile(check);
                        Matcher m = p.matcher(cell.trim());
                        System.out.println(m.matches());
                        if (!m.matches()) {
                            sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,不符合邮箱的填写格式!\r\n");
                        }
                    } catch (Exception e) {
                        //if(!m.matches()){
                        //手动捕捉异常
                        sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,不符合邮箱的填写格式!\r\n");
                        // }
                    }
                }
            }
        } else if (column == 4) {//说明是第四列（校验用户电话）
            if (cell.equals("") || cell == null) {
                //sb.append("@@导入数据第"+(row+1)+"行,第"+(column+1)+"列,用户电话为空！");
            } else {
                try {
//						^(0\\d{2}-\\d{8}(-\\d{1,4})?)|(0\\d{3}-\\d{7,8}(-\\d{1,4})?)$
                    Pattern pattern = Pattern.compile("(^0[0-9]{2,3}[-][1-9][0-9]{6,7}$)|(^[1-9][0-9]{6,7}$)");
                    Matcher isNum = pattern.matcher(cell);
                    System.out.println(isNum.matches());
                    if (!isNum.matches()) {
                        sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,不符合电话格式!\r\n");
                    }
                } catch (Exception e) {
                    //if (!isNum.matches()){
                    sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,不符合电话格式!\r\n");
                    //}
                }
            }
        } else if (column == 5) {//说明是第五列（校验用户手机）
            if (cell.trim().equals("") || cell.trim() == null) {
                sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,用户手机为空！\r\n");
            } else {
                try {
//						^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$
                    String reg = "^[1][3,4,5,7,8][0-9]{9}$";
                    Pattern pattern = Pattern.compile(reg);
                    Matcher isNum = pattern.matcher(cell);
                    System.out.println(isNum.matches());
                    if (!isNum.matches()) {
                        sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,不符合手机格式!\r\n");
                    }
                } catch (Exception e) {
                    //if (!isNum.matches()){
                    sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,不符合手机格式!");
                    //}
                }
            }
        } else if (column == 6) {//说明是第六列（校验用户所属机构）
            if (cell.trim().equals("") || cell.trim() == null) {
                sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,用户所属机构为空!\r\n");
            } else {
                //判断用户输入的所属组织机构id是否存在
                String orgName = cell.trim();
                List<SysOrganization> orgLst = sysOrganizationService.queryOrgByName(orgName);
                if (orgLst.isEmpty()) {
                    sb.append("@@导入数据第" + (row + 1) + "行,第" + (column + 1) + "列,所属机构，不存在!\r\n");
                }
            }
        }
        return sb.toString();
    }

    /*
     * 2017-06-29
     * jyh
     * 错误日志下载抽取至LogErrorsController中
     */
    /**
     * * <p>Title: 导入数据，错误文档</p>
     * <p>Company:@param response
     * <p>Company:@param request </p>
     * @author : xiaoliu
     * @date :2016年10月27日下午4:22:47
     */
	    /*@RequestMapping(value = "downLoadErr", method = RequestMethod.POST)
	    @ResponseBody
	    public void downLoadErr(HttpServletResponse response,HttpServletRequest request){
	    	String fileName = request.getParameter("err_fileName");
			String path = JspActionController.class.getProtectionDomain().getCodeSource().getLocation().getPath();
			String file=path.substring(1, path.indexOf("/WEB-INF/classes"))+"/error_text/"+fileName;
			System.out.println("file:"+file);
			try {
				InputStream inStream = new FileInputStream(file);
				if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){
				     fileName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
				}else{
				     fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
				}
				response.reset();
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/octet-stream; charset=UTF-8");
				response.addHeader("Content-Disposition",  "attachment;filename=\"" + fileName + "\"");
				// 循环取出流中的数据
				byte[] b = new byte[100];
				int len;
				OutputStream output=response.getOutputStream();
				while ((len = inStream.read(b)) > 0)
					output.write(b, 0, len);
				
				output.flush();
				output.close();
				inStream.close();
				//result=new Result
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				//e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}*/

    /**
     * 修改用户
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject updatePwd(HttpServletRequest request) {

        Map<String, Object> param = new HashMap<>();
        // 获取session中用户
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        int count = 0;
        //修改用户
        String pwd = request.getParameter("pwd");//确认密码
        String oldPwd = request.getParameter("oldPwd");//原始密码
        //给输入的初始密码加密
        String bianPwd = CipherUtil.createPwdEncrypt(user.getUserAccount().trim(), oldPwd.trim(), user.getUserSalt());
        if (bianPwd.equals(user.getUserPassword())) {//如果原始密码输入正确
            //将输入的确认密码加密
            String newPwd = CipherUtil.createPwdEncrypt(user.getUserAccount().trim(), pwd.trim(), user.getUserSalt());
            user.setUserPassword(newPwd);
            param.put("userId", user.getUserId());
            param.put("userPassword", newPwd);
            count = sysUserService.updatePwd(param);
        } else {
            count = -1;
        }

        ResultObject result = new ResultObject(count, "密码修改成功", "原始密码输入失败");
        //     System.out.println(result);
        return result;
    }

    //校验，当前批量导入的数据与数据库已存在数据进行校验
    public Map<String, Object> checkTabAcctImport(List<Object[]> valueList, String tableName) {
        StringBuffer sb = new StringBuffer();//声明拼接符
        boolean flag = true;
        Map<String, Object> checkAccMap = new HashMap<>();

        //查询用户里面的所有用户
        //List<SysUser> userLst = sysUserServiceImpl.queryUserByUserAccount(params);

        for (int i = 0; i < valueList.size(); i++) {//获取用户将导入的数据n条
            String[] row = (String[]) valueList.get(i);//获取行
            String actAccount = row[0];
            Map usmap = new HashMap();
            usmap.put("userAccount", actAccount);
            int count = sysUserService.selectUserAccount(usmap);
            if (count > 0) {//说明有重复
                flag = false;
                sb.append("此次导入的这批数据中,第" + (i + 1) + "行" + actAccount + "跟数据表里面存在重复！\r\n");
            }
        }

        checkAccMap.put("tflag", flag);
        checkAccMap.put("checkTabResult", sb.toString());
        return checkAccMap;
    }

    //校验，当前批量导入的数据，数据账号是否有重复
    public Map<String, Object> checkAccountImport(List<Object[]> valueList, String tableName) {
        StringBuffer sb = new StringBuffer();//声明拼接符
        boolean flag = true;
        Map<String, Object> checkAccMap = new HashMap<>();
        for (int i = 0; i < valueList.size(); i++) {//获取用户将导入的数据n条
            String[] row = (String[]) valueList.get(i);//获取行
            String actAccount = row[0];
            for (int j = i + 1; j < valueList.size(); j++) {
                if (actAccount.equals(valueList.get(j)[0])) {
                    sb.append("第" + (i + 1) + "个跟第" + (j + 1) + "个用户账号重复，值是：" + actAccount + "\r\n");
                    flag = false;
                }
            }
        }

        checkAccMap.put("flag", flag);
        checkAccMap.put("checkResult", sb.toString());
        return checkAccMap;
    }

}
